<template>
  <div class="dashboard module-container">
    <div class="module-header">
      <h2>{{ $t('dashboard.title') }}</h2>
      <p class="module-description">{{ $t('dashboard.description') }}</p>
    </div>

    <div class="dashboard-content">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in stats" :key="stat.label">
          <div class="stat-card">
            <div class="stat-icon">
              <i :class="stat.icon"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ $t(stat.labelKey) }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="module-grid">
        <el-col :span="8" v-for="module in modules" :key="module.id">
          <div class="module-card" @click="openModule(module.id)">
            <div class="module-icon">
              <i :class="module.icon"></i>
            </div>
            <h3>{{ module.name }}</h3>
            <p>{{ module.description }}</p>
            <el-button type="text" class="module-action">
              打开 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
        </el-col>
      </el-row>

      <div class="recent-section">
        <h3>{{ $t('dashboard.recentActivity') }}</h3>
        <el-table :data="recentHistory" style="width: 100%" :empty-text="$t('common.noData')">
          <el-table-column prop="type" :label="$t('dashboard.type')" width="100">
            <template slot-scope="scope">
              <el-tag size="mini" :type="getTypeTagType(scope.row.type)">
                {{ scope.row.type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="method" :label="$t('dashboard.method')" width="100" />
          <el-table-column prop="url" :label="$t('dashboard.urlOrTopic')" show-overflow-tooltip />
          <el-table-column prop="status" :label="$t('dashboard.status')" width="100">
            <template slot-scope="scope">
              <span :class="getStatusClass(scope.row.status)">
                {{ scope.row.status }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="timestamp" :label="$t('dashboard.time')" width="180">
            <template slot-scope="scope">
              {{ scope.row.timestamp | formatDateTime }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('dashboard.action')" width="100">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="loadHistoryItem(scope.row)"
              >
                {{ $t('common.reload') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="quick-actions">
        <h3>{{ $t('dashboard.quickActions') }}</h3>
        <div class="action-buttons">
          <el-button @click="newHttpRequest">
            <i class="el-icon-plus"></i> {{ $t('dashboard.newHttpRequest') }}
          </el-button>
          <el-button @click="startHttpServer">
            <i class="el-icon-s-platform"></i> {{ $t('dashboard.startHttpServer') }}
          </el-button>
          <el-button @click="connectMqtt">
            <i class="el-icon-connection"></i> {{ $t('dashboard.connectMqtt') }}
          </el-button>
          <el-button @click="importConfig">
            <i class="el-icon-upload"></i> {{ $t('dashboard.importConfig') }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  name: 'Dashboard',
  data() {
    return {
      stats: [
        {
          icon: 'el-icon-success',
          value: 0,
          labelKey: 'dashboard.successRequests'
        },
        {
          icon: 'el-icon-warning',
          value: 0,
          labelKey: 'dashboard.failedRequests'
        },
        {
          icon: 'el-icon-connection',
          value: 0,
          labelKey: 'dashboard.activeConnections'
        },
        {
          icon: 'el-icon-time',
          value: '0ms',
          labelKey: 'dashboard.avgResponseTime'
        }
      ]
    }
  },
  computed: {
    ...mapState('modules', ['availableModules']),
    ...mapState('history', ['items']),
    
    modules() {
      return this.availableModules.filter(m => m.enabled)
    },
    
    recentHistory() {
      return this.items.slice(0, 10)
    }
  },
  mounted() {
    this.loadStats()
  },
  methods: {
    ...mapActions('modules', ['loadModule']),
    ...mapActions('config', ['importConfig']),
    
    openModule(moduleId) {
      this.loadModule(moduleId)
      // 只在路由不同时进行导航
      if (this.$route.path !== `/${moduleId}`) {
        this.$router.push(`/${moduleId}`)
      }
    },
    
    loadStats() {
      const history = this.items
      const successCount = history.filter(h => h.success).length
      const failCount = history.filter(h => !h.success).length
      
      this.stats[0].value = successCount
      this.stats[1].value = failCount
      
      const responseTimes = history
        .filter(h => h.responseTime)
        .map(h => h.responseTime)
      
      if (responseTimes.length > 0) {
        const avgTime = responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length
        this.stats[3].value = `${avgTime.toFixed(0)}ms`
      }
    },
    
    getTypeTagType(type) {
      const types = {
        http: 'primary',
        mqtt: 'success',
        websocket: 'warning',
        tcp: 'info',
        udp: 'info'
      }
      return types[type] || 'info'
    },
    
    getStatusClass(status) {
      if (status >= 200 && status < 300) return 'status-success'
      if (status >= 400) return 'status-error'
      return ''
    },
    
    loadHistoryItem(item) {
      if (item.type === 'http' && item.request) {
        this.$store.dispatch('httpClient/loadRequestFromHistory', item.request)
        if (this.$route.path !== '/http-client') {
          this.$router.push('/http-client')
        }
      }
    },
    
    newHttpRequest() {
      if (this.$route.path !== '/http-client') {
        this.$router.push('/http-client')
      }
    },
    
    startHttpServer() {
      if (this.$route.path !== '/http-server') {
        this.$router.push('/http-server')
      }
    },
    
    connectMqtt() {
      if (this.$route.path !== '/mqtt-client') {
        this.$router.push('/mqtt-client')
      }
    },
    
    importConfig() {
      this.$store.dispatch('config/importConfig')
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../styles/variables.scss';

.dashboard {
  .dashboard-content {
    padding: $spacing-large;
  }
}

.stat-card {
  background: linear-gradient(135deg, #fff 0%, $primary-lighter 100%);
  border-radius: 16px;
  padding: 24px;
  display: flex;
  align-items: center;
  box-shadow: $box-shadow-card;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid $border-lighter;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(74, 144, 226, 0.1) 0%, transparent 70%);
    animation: pulse 3s infinite;
  }
  
  &:hover {
    transform: translateY(-4px) scale(1.02);
    box-shadow: $box-shadow-hover;
    border-color: $primary-light;
    
    .stat-icon {
      transform: rotate(10deg) scale(1.1);
    }
  }
  
  .stat-icon {
    width: 56px;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    margin-right: 20px;
    background: linear-gradient(135deg, $primary-color, $primary-dark);
    color: white;
    border-radius: 12px;
    transition: all 0.3s ease;
    position: relative;
    z-index: 1;
  }
  
  .stat-info {
    flex: 1;
    position: relative;
    z-index: 1;
  }
  
  .stat-value {
    font-size: 28px;
    font-weight: 700;
    background: linear-gradient(135deg, $text-primary, $primary-dark);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    line-height: 1.2;
  }
  
  .stat-label {
    font-size: $font-size-base;
    color: $text-secondary;
    margin-top: 4px;
    font-weight: 500;
  }
}

.module-grid {
  margin-top: $spacing-large;
}

.module-card {
  background: $card-bg;
  border-radius: 16px;
  padding: 32px 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: $box-shadow-card;
  border: 1px solid transparent;
  position: relative;
  overflow: hidden;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, $primary-color, $primary-dark);
    transform: scaleX(0);
    transition: transform 0.3s ease;
  }
  
  &:hover {
    transform: translateY(-8px) scale(1.02);
    box-shadow: $box-shadow-hover;
    border-color: $primary-light;
    background: linear-gradient(135deg, #fff 0%, $primary-lighter 100%);
    
    &::after {
      transform: scaleX(1);
    }
    
    .module-icon {
      background: linear-gradient(135deg, $primary-color, $primary-dark);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      transform: scale(1.1) rotate(5deg);
    }
    
    h3 {
      color: $primary-dark;
    }
  }
  
  .module-icon {
    font-size: 56px;
    color: $text-secondary;
    margin-bottom: 20px;
    transition: all 0.3s ease;
    display: inline-block;
  }
  
  h3 {
    margin: 16px 0 8px;
    color: $text-primary;
    font-size: 18px;
    font-weight: 600;
    transition: color 0.3s ease;
  }
  
  p {
    color: $text-secondary;
    font-size: $font-size-base;
    margin-bottom: 20px;
    line-height: 1.5;
  }
  
  .module-action {
    font-size: $font-size-base;
    font-weight: 600;
    color: $primary-color;
    
    i {
      transition: transform 0.3s ease;
    }
    
    &:hover i {
      transform: translateX(4px);
    }
  }
}

.recent-section {
  margin-top: $spacing-extra-large;
  background: $card-bg;
  border-radius: 16px;
  padding: 28px;
  box-shadow: $box-shadow-card;
  border: 1px solid $border-lighter;
  
  h3 {
    margin-top: 0;
    margin-bottom: $spacing-medium;
    color: $text-primary;
  }
  
  .status-success {
    color: $success-color;
  }
  
  .status-error {
    color: $danger-color;
  }
}

.quick-actions {
  margin-top: $spacing-large;
  background: linear-gradient(135deg, $primary-lighter 0%, #fff 100%);
  border-radius: 16px;
  padding: 28px;
  box-shadow: $box-shadow-card;
  border: 1px solid $border-lighter;
  
  h3 {
    margin-top: 0;
    margin-bottom: $spacing-medium;
    color: $text-primary;
  }
  
  .action-buttons {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    
    .el-button {
      flex: 1;
      min-width: 200px;
      padding: 12px 24px;
      font-weight: 500;
      border-radius: 10px;
      transition: all 0.3s ease;
      
      i {
        font-size: 16px;
        margin-right: 8px;
      }
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
      }
    }
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

@keyframes countUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>